<template>
  <div v-if="visible">
    <el-dialog :visible.sync="visible"
               title="选择用户"
               :modal="false"
               class="user-dialog add-or-updata"
               width="80%"
               :before-close="closeDialog"
               :close-on-click-modal="false"
               :close-on-press-escape="false">
      <div class="transfer">
        <!-- <el-tabs v-model="activeName"
                 @tab-click="tabChange">
          <el-tab-pane v-for="(item,index) in conditionList"
                       :key="index+'only'"
                       :label="item.condition"
                       :name="item.condition"> -->
        <div v-for="(item,index) in conditionList"
             :key="index+'only'"
             :label="item.condition"
             :name="item.condition">
          <el-row :gutter="20"
                  class="condition-table">
            <!-- 左侧 -->
            <el-col :span="11"
                    style="padding-left:0">
              <div class="no-add">
                <span style="font-size: 18px">用户列表</span>
              </div>
              <el-form :inline="true"
                       @submit.native.prevent
                       :model="dataForm"
                       ref="dataForm"
                       @keyup.enter.native="search"
                       style="display: flex;">
                <el-form-item prop="realName"
                              :rules="stringRule(false)">
                  <el-autocomplete v-model.trim="dataForm.realName"
                                   placeholder="姓名/首字母选择"
                                   @select="handleSelect"
                                   :fetch-suggestions="querySearch"
                                   clearable></el-autocomplete>
                </el-form-item>
                <el-form-item prop="phone"
                              :rules="stringRule(false)">
                  <el-input v-model.trim="dataForm.phone"
                            placeholder="手机号"
                            clearable></el-input>
                </el-form-item>
                <el-form-item prop="deptName"
                              class="dept-list">
                  <el-popover v-model.trim="deptListVisible"
                              ref="deptListPopover1"
                              placement="bottom-start"
                              trigger="click">
                    <el-tree :data="deptList"
                             :props="{ label: 'name', children: 'children' }"
                             node-key="id"
                             ref="deptListTree"
                             :highlight-current="true"
                             :expand-on-click-node="false"
                             accordion
                             @current-change="deptListTreeCurrentChangeHandle">
                    </el-tree>
                  </el-popover>
                  <div class="tree-input">
                    <el-input v-model.trim="dataForm.deptName"
                              v-popover:deptListPopover1
                              readonly
                              placeholder="部门">
                    </el-input>
                    <i class="el-icon-circle-close close"
                       @click.prevent="onClose1"
                       v-show="dataForm.deptName !== ''"></i>
                  </div>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary"
                             @click="search">{{ $t('query') }}</el-button>
                </el-form-item>
              </el-form>
              <el-table ref="staffTable"
                        height="350"
                        border
                        v-loading="listLoading"
                        :row-key="getRowKeyLeft"
                        :data="dataList.slice((current-1)*pageSize,current*pageSize)"
                        @selection-change="handleStaffChange"
                        :header-cell-style="{background:'#f5f8ff'}">
                <el-table-column type="selection"
                                 align="center"
                                 :reserve-selection="true"
                                 width="55"></el-table-column>
                <el-table-column label="序号"
                                 type="index"
                                 align="center"
                                 show-overflow-toolti
                                 width="55">
                </el-table-column>
                <el-table-column label="账号"
                                 prop="username"
                                 align="center"
                                 show-overflow-tooltip>
                  <!-- <template slot-scope="row">
                    <span>{{ row }}</span>
                  </template> -->
                </el-table-column>
                <el-table-column label="姓名"
                                 prop="realName"
                                 align="center"
                                 show-overflow-tooltip>
                  <!-- <template slot-scope="{row}">
                    <span>{{ row.name}}</span>
                  </template> -->
                </el-table-column>
                <el-table-column label="手机号"
                                 prop="phone"
                                 align="center"
                                 show-overflow-tooltip>
                  <!-- <template slot-scope="{row}">
                    <span>{{ row.number}}</span>
                  </template> -->
                </el-table-column>
                <el-table-column label="部门"
                                 prop="deptName"
                                 align="center"
                                 show-overflow-tooltip>
                  <!-- <template slot-scope="{row}">
                    <span>{{ row.name}}</span>
                  </template> -->
                </el-table-column>
              </el-table>
              <!-- <el-pagination @size-change="changePageSize"
                             :current-page.sync="current"
                             @current-change="pageIndexChange"
                             :total="dataList.length"
                             layout="prev,pager,next"></el-pagination> -->
              <el-pagination :current-page="page"
                             :page-sizes="[10, 20, 50, 100]"
                             :total="total"
                             layout="total, sizes, prev, pager, next"
                             @size-change="pageSizeChangeHandle"
                             @current-change="pageCurrentChangeHandle">
              </el-pagination>
            </el-col>
            <!-- 图标 -->
            <div class="icon-center">
              <p class="icon-right-if icon-return"
                 @click="addStaff(item.condition)"
                 v-if="dataList.length>0">
                <i class="el-icon-arrow-left"></i>
              </p>
              <p class="icon-right-else icon-return"
                 v-else>
                <i class="el-icon-arrow-left"></i>
              </p>
              <p class="icon-right-if"
                 @click="removeStaff(item.condition)"
                 v-if="selectedStaffList.length>0">
                <i class="el-icon-arrow-left"></i>
              </p>
              <p class="icon-right-else"
                 v-else>
                <i class="el-icon-arrow-left"></i>
              </p>
            </div>
            <!-- 右侧 -->
            <el-col :span="11"
                    style="padding-right:0; padding-top: 62px;">
              <div class="no-add">
                <span style="margin-top:-62px; font-size: 18px">已选用户</span>
              </div>
              <el-table ref="selectedStaffTable"
                        height="350"
                        border
                        v-loading="listLoading"
                        :row-key="getRowKeyRight"
                        :data="selectedStaffList.slice((pageRightNumber-1)*pageRightSize,pageRightNumber*pageRightSize)"
                        @selection-change="handleSelectedStaffChange"
                        :header-cell-style="{background:'#f5f8ff'}">
                <el-table-column type="selection"
                                 align="center"
                                 :reserve-selection="true"
                                 width="55"></el-table-column>
                <el-table-column label="序号"
                                 type="index"
                                 align="center"
                                 show-overflow-tooltip
                                 width="55">
                </el-table-column>
                <el-table-column label="账号"
                                 prop="username"
                                 align="center"
                                 show-overflow-tooltip>
                  <!-- <template slot-scope="{row}">
                    <span>{{ row.name}}</span>
                  </template> -->
                </el-table-column>
                <el-table-column label="姓名"
                                 prop="realName"
                                 align="center"
                                 show-overflow-tooltip>
                  <!-- <template slot-scope="{row}">
                    <span>{{ row.name}}</span>
                  </template> -->
                </el-table-column>
                <el-table-column label="手机号"
                                 prop="phone"
                                 align="center"
                                 show-overflow-tooltip>
                  <!-- <template slot-scope="{row}">
                    <span>{{ row.number}}</span>
                  </template> -->
                </el-table-column>
                <el-table-column label="部门"
                                 prop="deptName"
                                 align="center"
                                 show-overflow-tooltip>
                  <!-- <template slot-scope="{row}">
                    <span>{{ row.name}}</span>
                  </template> -->
                </el-table-column>
              </el-table>
              <!-- <el-pagination @size-change="changeRightPageSize"
                             @current-change="currentChange"
                             :current-page.sync="pageRightNumber"
                             small
                             layout="prev, pager, next"
                             :total="selectedStaffList.length"> </el-pagination> -->
              <el-pagination :current-page.sync="pageRightNumber"
                             :page-sizes="[10, 20, 50, 100]"
                             :total="selectedStaffList.length"
                             layout="total, sizes, prev, pager, next"
                             @size-change="changeRightPageSize"
                             @current-change="currentChange">
              </el-pagination>
            </el-col>
          </el-row>
        </div>
        <!-- </el-tab-pane>
        </el-tabs> -->
      </div>

      <template slot="footer">
        <el-button type="primary"
                   @click="dataFormSubmitHandle()">下一步</el-button>
      </template>
    </el-dialog>
    <!-- 权限设置 -->
    <purview-setting ref="permission" />
  </div>
</template>

<script>
import mixinViewModule from '@/mixins/view-module'
import minFormValidate from '@/mixins/form-validate'
import debounce from 'lodash/debounce'
import PurviewSetting from './purview-setting.vue'

export default {
  mixins: [mixinViewModule, minFormValidate],
  components: {
    PurviewSetting
  },
  data () {
    return {
      current: 1,
      pageSize: 10,
      pageRightNumber: 1,
      pageRightSize: 10,
      activeName: '用户',
      staffLeft: { // 用户左边表格数据
      // totalRow:0,
        dataList: [ // 项目中调用接口获取数据，此处是模拟数据
          { id: '1', name: '用户1', number: '9' },
          { id: '2', name: '用户2', number: '8' },
          { id: '3', name: '用户3', number: '7' },
          { id: '4', name: '用户4', number: '6' },
          { id: '5', name: '用户5', number: '9' },
          { id: '6', name: '用户6', number: '8' },
          { id: '7', name: '用户7', number: '7' },
          { id: '8', name: '用户8', number: '6' },
          { id: '9', name: '用户9', number: '9' },
          { id: '10', name: '用户10', number: '8' },
          { id: '11', name: '用户11', number: '7' }
        ]
      },
      conditionList: [{
        name: '条件',
        condition: '用户'
      }],
      selectedStaffList: [], // 右边表格
      listLoading: false,
      mixinViewModuleOptions: {
        activatedIsNeed: false,
        getDataListURL: '/system/sysUser/getUserPage', // 数据列表接口，API地址
        getDataListIsPage: true, // 数据列表接口，是否需要分页？
        getDeptListURL: '/system/sysUser/getDeptInUser',
        addURL: '/system/sysPosition/addPosition', // 添加或修改接口，API地址
        updateURL: '/system/sysPosition/updatePosition', // 添加或修改接口，API地址
        getDataInfoURL: '', // 数据详情，API地址
        deleteURL: '/system/sysPosition/delPosition', // 删除接口，API地址
        deleteIsBatch: true, // 删除接口，是否需要批量？
        exportURL: '' // 导出接口，API地址
      },
      jobList: [],
      input: '',
      visible: false,
      deptListVisible: false,
      deptList: [],
      dataForm: {}
    }
  },
  methods: {
    onClose1: debounce(function () {
      this.dataForm.deptId = ''
      this.dataForm.deptName = ''
      this.$forceUpdate()
    }, 1000, { 'leading': true, 'trailing': false }),
    getDeptList () {
      // 获取部门列表
      this.getDataList({ url: this.mixinViewModuleOptions.getDeptListURL }).then(res => {
        if (res.code !== 0) { return }
        this.deptList = res.data
        if (!res.data.length) {
          this.deptList.push({
            id: 0,
            name: this.$t('dept.parentNameDefault')
          })
        }
      })
    },
    // 上级部门树, 选中
    deptListTreeCurrentChangeHandle (data) {
      this.dataForm.deptName = data.name
      this.dataForm.deptId = data.id
      this.deptListVisible = false
    },
    closeDialog () {
      this.visible = false
      this.selectedStaffList = []
    },
    init (data) {
      this.jobList = []
      this.visible = true
      // this.getJobList()
      this.onClose1()
      this.getDataList()
      this.getDeptList()
    },
    // 行数据的Key
    getRowKeyLeft (row) {
      return row.id
    },
    getRowKeyRight (row) {
      return row.id
    },
    tabChange () {
      this.current = 1
      this.pageRightNumber = 1
    },
    pageIndexChange (current) {
      this.current = current
    },
    changePageSize (val) {
      this.pageSize = val
      this.tabChange()
    },
    changeRightPageSize (val) {
      this.pageRightSize = val
    },
    handleSizeChange (val) {
      this.pageSize = val
    },
    handleCurrentChange (val) {
      this.current = val
    },
    currentChange (val) {
      this.pageRightNumber = val
    },
    // 将左边表格选择项存入staffLeftSaveData中(后面与右边的对比，右边已存在再不添加)
    handleStaffChange (rows) {
      this.staffLeftSaveData = []
      if (rows) {
        rows.forEach(row => {
          if (row) {
            this.staffLeftSaveData.push(row)
          }
        })
      }
    },
    // 左边表格选择项移到右边
    addStaff (type) {
      let repeat = false
      setTimeout(() => {
        this.$refs['staffTable'][0].clearSelection()
        this.$refs['selectedStaffTable'][0].clearSelection()
      }, 0)
      for (const item of this.selectedStaffList) {
        this.staffLeftSaveData.map((res) => {
          if (res && item.id === res.id) {
            repeat = true
            this.$message.error(`该${type}已添加`)
          }
        })
        // if (this.staffLeftSaveData[0] && item.id === this.staffLeftSaveData[0].id) {
        //   repeat = true
        //   this.$message.error(`该${type}已添加`)
        //   return
        // }
      }
      if (!repeat) {
        this.staffLeftSaveData.forEach(item => {
          this.selectedStaffList.push(item)
        })
        for (let i = 0; i < this.dataList.length; i++) {
          for (let j = 0; j < this.staffLeftSaveData.length; j++) {
            if (this.dataList[i] && this.staffLeftSaveData[j] && this.dataList[i].id === this.staffLeftSaveData[j].id) {
              this.dataList.splice(i, 1)
            }
          }
        }
      }
      if (this.dataList.length === 0 && this.page !== 1) {
        this.page--
      }
    },
    // 右边表格选择项移到左边
    removeStaff (type) {
      setTimeout(() => {
        this.$refs['staffTable'][0].clearSelection()
        this.$refs['selectedStaffTable'][0].clearSelection()
      }, 0)
      this.selectedStaffData.forEach(item => {
        this.dataList.push(item)
      })
      const removeDuplicateObj = (arr) => {
        let newArr = []
        let obj = {}
        for (var i = 0; i < arr.length; i++) {
          if (!obj[arr[i].id]) {
            newArr.push(arr[i])
            obj[arr[i].id] = true
          }
        }
        return newArr
      }
      this.dataList = removeDuplicateObj(this.dataList)
      for (let i = 0; i < this.selectedStaffList.length; i++) {
        for (let j = 0; j < this.selectedStaffData.length; j++) {
          if (this.selectedStaffList[i] && this.selectedStaffData[j] && this.selectedStaffList[i].id === this.selectedStaffData[j].id) {
            this.selectedStaffList.splice(i, 1)
          }
        }
      }
    },
    // 将右边表格选择项存入selectedStaffData中
    handleSelectedStaffChange (rows) {
      this.selectedStaffData = []
      if (rows) {
        rows.forEach(row => {
          if (row) {
            this.selectedStaffData.push(row)
          }
        })
      }
    },
    /**
     * @description: 校验字符串是否为字母汉字数字
     * @example: this.checkRule(123) this.checkRule('你好') this.checkRule('hello')
     * @param {string} str 要校验的字符串
     * @return {number} -1:非字母非文字非数字或不存在,1:字母,2:文字,3:数字
     */
    checkRule (str) {
      let results = -1
      if (str) {
        if (/^[a-zA-Z]*$/g.test(str)) { // 字母
          results = 1
        } else if (/^[\u4E00-\u9FA5]+$/.test(str)) { // 文字
          results = 2
        } else if (/^[0-9]*$/g.test(str)) { // 数字
          results = 3
        }
      }
      return results
    },
    querySearch (queryString, cb) {
      let str = ''
      if (this.checkRule(queryString) === -1 || this.checkRule(queryString) === 2) {
        str = `realName=${queryString}`
      } else if (this.checkRule(queryString) === 1) {
        if (!str.length === 1) return
        str = `initial=${queryString}`
      } else if (this.checkRule(queryString) === 3) {
        str = `username=${queryString}`
      }
      if (queryString === '') {
        str = ''
      }
      this.$http.get(`/system/sysUser/getByName?${str}`).then(({ data: res }) => {
        if (res.code !== 0) {
          return
        }
        let temp = res.data || []
        let restaurants = []
        temp.map((item) => {
          restaurants.push({
            value: item.username ? '' + item.username + '(' + item.realName + ')' : '',
            userId: item.id,
            name: item.realName,
            deptName: item.deptName,
            deptId: item.deptId,
            phone: item.phone,
            dept: item.dept
          })
        })
        // 调用 callback 返回建议列表的数据
        cb(restaurants)
      })
    },
    handleSelect (item) {
      this.dataForm.realName = item.name
      this.search()
    },
    // 查询
    search () {
      // const param = {}
      this.page = 1
      this.getDataList({ paramData: {
        realName: this.dataForm.realName,
        phone: this.dataForm.phone,
        deptId: this.dataForm.deptId
      }
      })
    },
    // 表单提交
    dataFormSubmitHandle: debounce(function () {
      if (this.selectedStaffList.length === 0) {
        this.$message.warning('请先选择用户')
      } else {
        this.$refs.permission.init(this.selectedStaffList)
      }
    }, 1000, { 'leading': true, 'trailing': false })
  }
}
</script>

<style lang="scss" scoped>
::deep .el-dialog__body {
  padding: 10px 20px 30px 20px;
}
.transfer {
  // width: 1160px;
  // box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
  // padding: 30px;
  margin: auto;
  .condition-table {
    display: flex;
    justify-content: space-between;
    align-items: center;
    ::deep.el-table__body-wrapper {
      overflow-y: auto;
    }
    ::deep.el-table__body-wrapper::-webkit-scrollbar {
      width: 12px;
      height: 12px;
    }
    ::deep.el-table__body-wrapper::-webkit-scrollbar-thumb {
      background-color: #9093994d;
      border-radius: 6px;
    }
  }

  .el-icon-arrow-left {
    font-size: 21px !important;
    background: #d9d9d9;
    border-radius: 4px;
    color: #fff;
    padding: 2px;
  }
  ::deep .el-popover__reference-wrapper {
    vertical-align: middle !important;
    padding-left: 4px;
  }
  .icon-right-if .el-icon-arrow-left {
    background: #409eff;
    color: #fff;
  }
  .icon-center {
    i {
      margin-top: 8px;
      &:hover {
        cursor: pointer;
      }
    }
    .icon-return {
      transform: rotate(180deg);
    }
  }
  .no-add {
    display: flex;
    justify-content: space-between;
    height: 30px;
    line-height: 30px;
    font-size: 14px;
    margin-bottom: 10px;
    span {
      color: #333;
    }
  }
}
.dept-list ::deep .el-form-item__content {
  line-height: 0 !important;
}
.add-or-updata ::deep .el-input__inner {
  border-radius: 4px;
  border-bottom: none;
  border: 1px solid #dcdfe6;
}
.tree-input {
  width: 100%;
  position: relative;
  .close {
    position: absolute;
    right: 10px;
    top: 13px;
    font-size: 16px;
    color: #858585;
    cursor: pointer;
    background-color: white;
  }
}
</style>
